package com.lzymall.controller.common;

import com.lzymall.common.Const;
import com.lzymall.pojo.User;
import com.lzymall.util.CookieUtil;
import com.lzymall.util.JsonUtil;
import com.lzymall.util.RedisShardedPoolUtil;
import org.apache.commons.lang3.StringUtils;

import javax.jws.soap.SOAPBinding;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @Author: lizhenyao
 * @Desciption:
 */
public class SessionExpireFilter implements Filter{
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        String loginToken = CookieUtil.readLoginToken(request);
        if (StringUtils.isNotEmpty(loginToken)){
            //如果loginToken部位空的化,那么继续从Redis中拿去json字符串
            String userJsonStr = RedisShardedPoolUtil.get(loginToken);
            //反序列化
            User user = JsonUtil.string2Obj(userJsonStr, User.class);
            if (user != null){
                //确定用户已经登录,重新设置用户的session有效时间
                RedisShardedPoolUtil.expire(userJsonStr, Const.RedisCacheExtime.REDIS_CHACHE_EXTIME);
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
